package com.lemon.smartsafety.ui.fragment;

import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.lemon.android.http.HttpUtils;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.event.main.drawer.DrawerClickEvent;
import com.lemon.smartsafety.entity.event.main.drawer.DrawerClickEventForMain;
import com.lemon.smartsafety.entity.event.main.drawer.DrawerOpenEvent;
import com.lemon.smartsafety.entity.event.main.drawer.DrawerRefreshEvent;
import com.lemon.smartsafety.ui.adapter.DrawerAdapter;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafety.utils.Blur;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.ImgLoadUtil;
import com.lemon.smartsafety.utils.app.SharedPreferencesHelper;
import com.lemon.smartsafety.utils.common.AppUtils;
import com.lemon.smartsafety.utils.common.BitmapUtils;
import com.lemon.smartsafety.utils.common.StringUtils;

import org.greenrobot.eventbus.Subscribe;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Cooliean on 16/1/15.
 */
public class DrawerFragment extends BaseFragment {

    private static final int DOWNSCALE = 8;
    private static final int BLUR_RADIUS = 15;

    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerLayout mDrawerLayout;
    private View mFragmentContainerView;
    private Bitmap mBitmap;
    private Bitmap bitmap;
    private DrawerClickEvent mDrawerClickEvent;
    private SharedPreferencesHelper mSharedPreferencesHelper;
    private DrawerAdapter mDrawerAdapter;

    @Bind(R.id.main_left_img_avatar)
    CircleImageView mainLeftImgAvatar;

    @Bind(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @Bind(R.id.item_head)
    View head;

    @Bind(R.id.tvUserName)
    TextView tvUserName;

    @Bind(R.id.tvUserType)
    TextView tvUserType;

    @Bind(R.id.tvUserArea)
    TextView tvUserArea;

    @Bind(R.id.tv_app_version_code)
    TextView tvVersionCode;


    @Override
    protected void initViews() {
        mSharedPreferencesHelper = new SharedPreferencesHelper(IApplication.context());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mRecyclerView.getContext());
        mDrawerAdapter = new DrawerAdapter(getActivity());
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(mDrawerAdapter);
        head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mDrawerAdapter != null) {
                    mDrawerAdapter.clickProfile();
                }
            }
        });
        try {
            if (!CommonUtil.strIsEmpty(mSharedPreferencesHelper.getUserPhotoUrl())) {
                ImgLoadUtil.setImgPath(StringUtils.nullValue(HttpUtils.formatFilesUrl(mSharedPreferencesHelper.getUserPhotoUrl())), mainLeftImgAvatar);
            } else {
                mainLeftImgAvatar.setImageDrawable(getResources().getDrawable(R.mipmap.user_no_photo));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        setLoginText();
    }

    private void setLoginText() {
        if (AppService.getInstance().isLogin()) {
            tvUserName.setText(mSharedPreferencesHelper.getUserName());
            tvUserType.setText(StringUtils.nullValue(mSharedPreferencesHelper.getUserTypeName()));
            tvUserArea.setText(mSharedPreferencesHelper.getUserPlaceInfo());
        } else {
            tvUserName.setText(getText(R.string.login_no));
            tvUserType.setText(getText(R.string.empty));
            tvUserArea.setText(getText(R.string.empty));
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
        tvVersionCode.setText("V" + AppUtils.getVersionName(IApplication.context()));
    }

    public boolean isDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
    }

    public void openDrawer() {
        mDrawerLayout.openDrawer(mFragmentContainerView);
    }


    public void closeDrawer() {
        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_drawer;
    }

    @Override
    protected void getBaseArguments() {

    }


    public void setUp(final FrameLayout mContentLayout, int fragmentId, final DrawerLayout drawerLayout) {
        mFragmentContainerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;

        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                //菜单关闭的时候开始发送切换事件
                if (mDrawerClickEvent != null) {
                    mDrawerClickEvent.setEventResult(Constants.Result.SUCCESS);
                    DrawerClickEventForMain mainEvent = new DrawerClickEventForMain(mDrawerClickEvent.getDrawId());
                    mainEvent.setEventResult(Constants.Result.SUCCESS);
                    AppService.getBus().post(mainEvent);
                }
                //每次关闭的时候都处理一下显示的问题
                setLoginText();
                getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
                if (mBitmap != null) {
                    mBitmap.recycle();
                    mBitmap = null;
                }
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (!isAdded()) {
                    return;
                }
                //每次关闭的时候都处理一下显示的问题
                setLoginText();
                getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, slideOffset);
                if (mBitmap != null) {
                    bitmap = Bitmap.createBitmap(mBitmap, 0, 0, (int) (mBitmap.getWidth() * slideOffset) > 0 ? (int) (mBitmap
                            .getWidth() * slideOffset) : 1, mBitmap.getHeight());
                    BitmapDrawable bd;
                    bd = new BitmapDrawable(bitmap);
                    drawerView.setBackgroundDrawable(bd);

                } else {
                    mBitmap = BitmapUtils.drawViewToBitmap(mContentLayout, rootView.getWidth(), rootView.getHeight(), DOWNSCALE, "#42283593");
                    mBitmap = Blur.fastblur(mContentLayout.getContext(), mBitmap, BLUR_RADIUS);
                }

            }

        };
        // Defer code dependent on restoration of previous instance state.
        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });

        mDrawerLayout.setDrawerListener(mDrawerToggle);

    }

    /**
     * @param event
     */
    @Subscribe
    public void onEventMainThread(DrawerRefreshEvent event) {
        if (event.getPosition() != -1) {
            mDrawerAdapter.setSelectedPosition(event.getPosition());
        } else {
            mDrawerAdapter.notifyDataSetChanged();
            try {
                if (!CommonUtil.strIsEmpty(mSharedPreferencesHelper.getUserPhotoUrl())) {
                    ImgLoadUtil.setImgPath(StringUtils.nullValue(HttpUtils.formatFilesUrl(mSharedPreferencesHelper.getUserPhotoUrl())), mainLeftImgAvatar);
                } else {
                    mainLeftImgAvatar.setImageDrawable(getResources().getDrawable(R.mipmap.user_no_photo));
                }
                setLoginText();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param event
     */
    @Subscribe
    public void onEventMainThread(DrawerOpenEvent event) {
        if (Constants.Result.ERROR.equals(event.getEventResult())) {
            closeDrawer();
            return;
        }
        openDrawer();
    }

    /**
     * @param drawerClickEvent
     */
    @Subscribe
    public void onEventMainThread(DrawerClickEvent drawerClickEvent) {
        if (Constants.Result.SUCCESS.equals(drawerClickEvent.getEventResult())) {
            return;
        }
        mDrawerClickEvent = drawerClickEvent;
        closeDrawer();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
